/* eslint-disable */
import Request from './request';
import mHelper from './helper';
import store from '@/store';
import config from '@/config/config.js';
let refreshToken = '/v1/ste'
let indexConfig = {}
const http = new Request();


function isWeiXin() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	}
}
// #ifdef MP
const accountInfo = uni.getAccountInfoSync()
console.log('accountInfo', accountInfo)
uni.setStorageSync('appId', accountInfo.miniProgram.appId)
// #endif
async function getConfig() {
	uni.setStorageSync('requestconfig', config)
	indexConfig = config
	// request全局参数设置
	http.setConfig(config => {
		/* 设置全局配置 */
		config.header = indexConfig.header;
		config.param = indexConfig.param;
		config.baseUrl = indexConfig.baseUrl; /* 根域名不同 */
		const systemInfo = uni.getSystemInfoSync();
		const systemInfoHeaders = {
			'appid': uni.getStorageSync('appId'),
			'device-name': systemInfo.brand, // 设备名称
			// 'width': systemInfo.screenWidth, // 屏幕宽度
			// 'height': systemInfo.screenHeight, // 屏幕高度
			'os': systemInfo.platform, // 客户端平台
			'os-version': systemInfo.system // 操作系统版本
		};
		config.loading = false,
			config.header = {
				...config.header,
				...systemInfoHeaders
			};
		//console.log('indexConfig', indexConfig)
		return config;
	});
}
getConfig()
let isRefreshing = false;
let requests = [];
http.interceptor.request((config, cancel) => {
	/* 请求之前拦截器 */
	config.header['token'] = uni.getStorageSync('app:token');
	config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('app:token');
	/* 单商户
	 config.header['merchant-id'] = uni.getStorageSync('merchantId') || 1;
	*/
	/* 支付密码截器*/
	if (config.method == 'POST' && typeof config.data.pay_password == 'string' && config.data.pay_password ==
		'') {
		console.log('支付密码截器')
		uni.$emit('openPayPassword')
		config.is_exit = true
		return cancel('须要输入支付密码', config)
		// return new Promise((resolve, reject) => {
		// 	reject('须要输入支付密码');
		// });
		// return Promise.reject('须要输入支付密码');
	}
	//console.log('http.interceptor.request(config', config)
	return config;
}, error => {
	return Promise.reject(error);
});
// 刷新refreshToken
async function handleRefreshToken(refresh_token) {
	const params = {};
	params.group = mHelper.platformGroupFilter();
	params.refresh_token = refresh_token;
	await http.post(refreshToken, params).then(async r => {
		store.commit('login', r.data);
		isRefreshing = false;
	});
}
http.interceptor.response(async response => {
		/* 请求之后拦截器 */
		//console.log(response)
		switch (response.data.code) {
			case 0:
				return response.data.data;
			case 400:
				uni.showToast({
					icon: 'error',
					title: response.data.msg,
					duration: 2000
				});
				return Promise.reject(response.data.msg);
			case 401:
				isRefreshing = false;
				// refreshToken 的返回状态为401
				let author_login = uni.getStorageSync('requestconfig').author_login
				let author_address = uni.getStorageSync('requestconfig').author_address

				uni.$emit('openUserLogin')

				let key = parseInt(Math.random() * (10000 - 0 + 1) + 0);
				uni.setStorageSync("loginKey", key)
				mHelper.backToLogin();
				uni.removeStorageSync('app:token');
				//await store.commit('logout');
				uni.$emit('openUserLogin')
				uni.navigateTo({
					url: '/login/login'
				})
				throw response.data.message;
				break;
			case 405:
				mHelper.toast('当前操作不被允许');
				return Promise.reject(response.data.message);
			case 404:
				mHelper.toast(response.data.message);
				if (response.data.message == '页面未找到。' && response.config.url != '/log/error') {
					http.post('/log/error', {
						url: response.config.url,
						post: response.data,
						data: response.config.data,
						user: uni.getStorageSync('app:userInfo'),
						device: response.config.header
					})
				}
				return Promise.reject(response.data.message);
			case 429:
				mHelper.toast('请求过多，先休息一下吧');
				return Promise.reject(response.data.message);
			case 500:
				mHelper.toast('服务器繁忙～');
				// if (process.env.NODE_ENV !== 'development') {
				http.post('/log/error', {
					url: response.config.url,
					post: response.data,
					data: response.config.data,
					user: uni.getStorageSync('app:userInfo'),
					device: response.config.header
				})
				// }
				return Promise.reject(response.data.message);
			default:
				uni.showToast({
					icon: 'error',
					title: response.data.msg,
					duration: 2000
				});
				return Promise.reject(response.data.msg);
		}
	},
	error => {
		return Promise.reject(error);
	});
export {
	http
};